<!--
 * @Author: caihongtai caihongtai
 * @Date: 2025-02-13 21:35:36
 * @LastEditors: caihongtai caihongtai
 * @LastEditTime: 2025-04-11 14:41:10
 * @FilePath: /ai-interview-vue/src/views/Profile/recharge/index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <nav-bar title="充值中心" />
    <div class="recharge-container">
        <!-- 可用时长展示 -->
        <div class="available-time">
            <div class="time-container">
                <div class="time-number">{{ formatSeconds(availableMinutes) }}</div>
                <div class="time-text">当前可用面试时长(分钟)</div>
            </div>
            <img src="/images/mine/recharge/wallet.png" class="recharge-bg" />
        </div>

        <!-- 充值套餐列表 -->
        <div class="package-container">
            <div class="package-list">
                <div v-for="item in packages" :key="item.id" class="package-item"
                    :class="{ active: selectedPackage?.id === item.id }" @click="selectPackage(item)">
                    <div class="package-tag" v-if="item.tag">{{ item.tag }}</div>
                    <div class="package-price">
                        <span class="currency">¥</span>
                        <span class="amount">{{ item.price }}</span>
                    </div>
                    <div class="package-time">{{ item.minutes }}分钟</div>
                </div>
            </div>

            <!-- 协议说明 -->
            <div class="agreement">
                充值代表你已阅读并同意
                <span class="link" @click="showAgreement">《充值协议》</span>
            </div>
            <!-- 底部支付按钮 -->
            <div class="bottom-button">
                <van-button block type="primary" :disabled="!selectedPackage" @click="handlePay">
                    点击微信充值
                </van-button>
            </div>
            <div class="tips-contain">
                <div>价格说明：通过支付金额获取对应面试时长；其中，首充福利 仅第一次充值时可使用。</div>
                <div>
                    <div>售后说明：</div>
                    <div>尊敬的用户，感谢您选择我们的虚拟产品服务。请您仔细阅读以下售后相关内容：</div>
                    <ul>
                        <li>1.充值到账时间：本产品为虚拟产品，充值成功后将立即到账，您可以即时享受相关服务。</li>
                        <li>2. 退换货政策：鉴于商品的特殊性，虚拟产品一经售出，概不支持退换。请您在购买前充分了解并确认自身需求，谨慎操作。如有任何疑问，请联系<span
                                class="blue">loster1214@163.com</span></li>
                    </ul>
                </div>

            </div>
        </div>


        <!-- 支付确认弹窗 -->
        <van-dialog v-model:show="showPayConfirm" title="支付确认" :show-cancel-button="true" confirm-button-text="我已完成支付"
            cancel-button-text="重新支付" @confirm="checkPayStatus" @cancel="handlePay">
            <div class="pay-confirm-content">
                请确认是否已完成支付？
            </div>
        </van-dialog>
    </div>
</template>

<script setup>
    import { showToast } from 'vant'
    import { payApi } from '@/api/pay'
    import { usePayment } from '@/composables/usePayment'
    import NavBar from '@/components/NavBar/index.vue'
    import { userApi } from '@/api/user'
    import { formatSeconds } from '@/utils/untils'
    const router = useRouter()
    const { createOrder, checkOrder, initWxConfig } = usePayment()

    // 状态管理
    const availableMinutes = ref(0)
    const selectedPackage = ref({
        id: 1,
        price: 5.9,
        minutes: 30,
        tag: '首充福利'
    },); // 默认选中第一个套餐
    const showPayConfirm = ref(false)
    const currentOrderNo = ref('')
    // 充值套餐配置
    const packages = [
        {
            id: 1,
            price: 5.9,
            minutes: 30,
            tag: '首充福利'
        },
        {
            id: 2,
            price: 18.8,
            minutes: 60
        },
        {
            id: 3,
            price: 36.8,
            minutes: 120,
            tag: '最划算'
        }
    ]

    // 获取可用时长
    const getAvailableTime = async () => {
        try {
            const res = await userApi.getUserInfo()
            availableMinutes.value = res.data.available_seconds || 0
        } catch (error) {
            console.error('获取可用时长失败:', error)
        }
    }

    // 选择套餐
    const selectPackage = (item) => {
        selectedPackage.value = item
        console.log(selectedPackage.value)
    }

    // 显示充值协议
    const showAgreement = () => {
        router.push('/agreement/recharge')
    }


    // 处理支付
    const handlePay = async () => {
        if (!selectedPackage.value) return

        try {
            // 创建订单
            const orderRes = await createOrder({
                packageId: selectedPackage.value.id,
                amount: selectedPackage.value.price,
                minutes: selectedPackage.value.minutes
            })

            currentOrderNo.value = orderRes.orderNo

            // 调起微信支付
            await initWxConfig()
            wx.chooseWXPay({
                timestamp: orderRes.timestamp,
                nonceStr: orderRes.nonceStr,
                package: orderRes.package,
                signType: orderRes.signType,
                paySign: orderRes.paySign,
                success: () => {
                    showPayConfirm.value = true
                },
                fail: (res) => {
                    showToast('支付失败，请重试')
                    console.error('微信支付失败:', res)
                }
            })
        } catch (error) {
            showToast('创建订单失败，请重试')
            console.error('创建订单失败:', error)
        }
    }

    // 检查支付状态
    const checkPayStatus = async () => {
        try {
            const status = await checkOrder(currentOrderNo.value)
            if (status.success) {
                showToast('充值成功')
                getAvailableTime() // 刷新可用时长
            } else {
                showToast('支付未完成，请重试')
            }
        } catch (error) {
            showToast('查询支付状态失败，请稍后再试')
            console.error('查询支付状态失败:', error)
        }
    }

    onMounted(() => {
        getAvailableTime()
    })
</script>

<style lang="scss" scoped>
    .recharge-container {
        min-height: 100vh;
        background: #f7f8fa;
    }

    .available-time {
        padding: 40px 16px;
        background: linear-gradient(180deg, #f5e6ff 0%, #ffffff 100%);
        position: relative;

        .time-container {
            position: relative;
            z-index: 1;
        }

        .time-number {
            font-size: 48px;
            font-weight: bold;
            color: #333;
        }

        .time-text {
            font-size: 14px;
            color: #666;
            margin-top: 8px;
        }

        .recharge-bg {
            position: absolute;
            bottom: 0;
            right: 20px;
            width: 141px;
            height: 161px;
        }
    }

    .package-container {
        background: rgba(255, 255, 255, 1);
        height: calc(100vh - 200px);
        position: absolute;
        top: 25%;
        left: 0;
        right: 0;
    }

    .package-list {
        padding: 16px;
        display: grid;
        border-radius: 20px;
        grid-template-columns: repeat(3, 1fr);
        gap: 12px;

        .package-item {
            position: relative;
            background: #fff;
            border-radius: 12px;
            padding: 16px;
            text-align: center;
            border: 1px solid #eee;
            cursor: pointer;

            &.active {
                border-color: #8a2be2;
                background: rgba(138, 43, 226, 0.05);
            }

            .package-tag {
                position: absolute;
                top: -10px;
                left: 10px;
                transform: translateX(-50%);
                color: #fff;
                font-size: 10px;
                padding: 2px 4px;
                opacity: 1;
                border-radius: 4px;
                background: linear-gradient(90deg, rgba(255, 59, 144, 1) 0%, rgba(255, 59, 82, 1) 100%);
            }

            .package-price {
                margin-top: 8px;

                .currency {
                    font-size: 20px;
                    color: #333;
                }

                .amount {
                    font-size: 32px;
                    font-weight: bold;
                    color: #333;
                }
            }

            .package-time {
                font-size: 16px;
                color: #666;
                margin-top: 4px;
            }
        }
    }

    .agreement {
        text-align: center;
        font-size: 12px;
        color: #999;
        margin-top: 16px;

        .link {
            color: rgba(22, 93, 255, 1);
        }
    }

    .bottom-button {
        padding: 16px;
        background: #fff;

        .van-button {
            border-radius: 8px;
            background: rgba(160, 59, 255, 1);
            border: none;
        }
    }

    .pay-confirm-content {
        padding: 20px;
        text-align: center;
        color: #333;
    }

    .tips-contain {
        padding: 16px;
        font-size: 12px;
        font-weight: 400;
        letter-spacing: 0px;
        line-height: 20px;
        color: rgba(134, 144, 156, 1);

        .blue {
            color: rgba(22, 93, 255, 1);
        }
    }
</style>